package algorithm.string;

/**
 * 58. Length of Last Word
 * leetcode : https://leetcode.com/problems/length-of-last-word/
 * Difficulty : Easy
 *
 * 找一个字符串里最后一个单词的长度。
 * 需要注意的是，得排除掉最后的几个空格，再开始计数
 *
 * @Author Antony
 * @Since 2018/11/16 14:17
 */
public class LengthOfLastWord {

    public static void main(String[] args) {
        String str = "hello world";
        System.out.println(lengthOfLastWord(str));

        String s2 = "a  ";
        System.out.println(lengthOfLastWord(s2));
    }


    /**
     * 3ms - 99.22%
     * @param s
     * @return
     */
    public static int lengthOfLastWord(String s) {
        int len = 0;
        int idx = s.length()-1;
        boolean count = false;
        while(idx >=0){
            if(s.charAt(idx) != ' '){
                count = true;
                len++;
            }else if(count){
                break;
            }
            idx--;
        }
        return len;
    }
}
